package com.wh1200.mybatis.xmlless.plugin.visitor

import com.wh1200.mybatis.xmlless.util.TypeUtil
import net.sf.jsqlparser.schema.Table
import net.sf.jsqlparser.statement.select.FromItem
import net.sf.jsqlparser.statement.select.PlainSelect

/**
 *
 * @author 吴昊
 * @date 2024/1/29 18:55
 * @since v0.0.0
 * @version 1.0
 */

interface BaseSelectVisitor {

  fun getTables(): MutableMap<String, Class<*>>

  fun processSelectBody(selectBody: PlainSelect) {
    val fromItem = selectBody.fromItem
    val fromVisitor = processFromItem(fromItem)
    selectBody.joins?.forEach {
      it.rightItem.accept(fromVisitor)
    }
    getTables().putAll(fromVisitor.getTables())
    selectBody.where?.accept(ReplaceExpressionVisitor(getTables()))
  }


  fun processFromItem(fromItem: FromItem?): FromVisitor {
    val fromVisitor = FromVisitor()
    if (fromItem is Table && fromItem.alias == null) {
      getTables()[""] = TypeUtil.resolve<Any>(fromItem.name)
    }
    fromItem?.accept(fromVisitor)
    return fromVisitor
  }


}
